<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/little-eight-china.github.io/lib/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/little-eight-china.github.io/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/little-eight-china.github.io/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/little-eight-china.github.io/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/little-eight-china.github.io/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/little-eight-china.github.io/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/little-eight-china.github.io/',
    scheme: 'Gemini',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="十大基础排序算法冒泡排序 基本思路对n个数进行排序，每次都是由前一个数跟后一个数比较，每循环一轮， 就可以将最大的数移到数组的最后， 总共循环n-1轮，完成对数组排序。  动图演示     编码12345678910111213141516public static void sort(int[] arr) &amp;#123;		if (arr == null)			return;		int len =">
<meta name="keywords" content="little_eight">
<meta property="og:type" content="article">
<meta property="og:title" content="十大基础排序算法">
<meta property="og:url" content="http://yoursite.com/2019/01/30/十大基础排序算法/index.html">
<meta property="og:site_name" content="八达博客">
<meta property="og:description" content="十大基础排序算法冒泡排序 基本思路对n个数进行排序，每次都是由前一个数跟后一个数比较，每循环一轮， 就可以将最大的数移到数组的最后， 总共循环n-1轮，完成对数组排序。  动图演示     编码12345678910111213141516public static void sort(int[] arr) &amp;#123;		if (arr == null)			return;		int len =">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b1a3ac5e8?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b2349fb70?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b284a6b98?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b7d4cfe55?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b7f84849b?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b83823cd8?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bbe480b52?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bd10a5893?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bbf2b9faf?imageslim">
<meta property="og:updated_time" content="2019-02-27T13:41:58.859Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="十大基础排序算法">
<meta name="twitter:description" content="十大基础排序算法冒泡排序 基本思路对n个数进行排序，每次都是由前一个数跟后一个数比较，每循环一轮， 就可以将最大的数移到数组的最后， 总共循环n-1轮，完成对数组排序。  动图演示     编码12345678910111213141516public static void sort(int[] arr) &amp;#123;		if (arr == null)			return;		int len =">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b1a3ac5e8?imageslim">






  <link rel="canonical" href="http://yoursite.com/2019/01/30/十大基础排序算法/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>十大基础排序算法 | 八达博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/little-eight-china.github.io/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">八达博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/little-eight-china.github.io/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/little-eight-china.github.io/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档<span class="badge">15</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/little-eight-china.github.io/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类<span class="badge">4</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/little-eight-china.github.io/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签<span class="badge">2</span></a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/little-eight-china.github.io/2019/01/30/十大基础排序算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/little-eight-china.github.io/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="八达博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">十大基础排序算法
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-30 16:20:12" itemprop="dateCreated datePublished" datetime="2019-01-30T16:20:12+00:00">2019-01-30</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-02-27 13:41:58" itemprop="dateModified" datetime="2019-02-27T13:41:58+00:00">2019-02-27</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/little-eight-china.github.io/categories/杂类/" itemprop="url" rel="index"><span itemprop="name">杂类</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="十大基础排序算法"><a href="#十大基础排序算法" class="headerlink" title="十大基础排序算法"></a>十大基础排序算法</h2><h3 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h3><ul>
<li><p>基本思路<br>对n个数进行排序，每次都是由前一个数跟后一个数比较，每循环一轮， 就可以将最大的数移到数组的最后， 总共循环n-1轮，完成对数组排序。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b1a3ac5e8?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">int</span> len = arr.length;</span><br><span class="line">		<span class="comment">// i控制循环次数，长度为len的数组只需要循环len-1次，i的起始值为0所以i&lt;len-1</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len - <span class="number">1</span>; i++) &#123;</span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; len - i - <span class="number">1</span>; j++) &#123;</span><br><span class="line">				<span class="comment">// 如果前一个数比后一个数大，则交换位置将大的数往后放。</span></span><br><span class="line">				<span class="keyword">if</span> (arr[j] &gt; arr[j + <span class="number">1</span>]) &#123;</span><br><span class="line">					<span class="keyword">int</span> temp = arr[j + <span class="number">1</span>];</span><br><span class="line">					arr[j + <span class="number">1</span>] = arr[j];</span><br><span class="line">					arr[j] = temp;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<a id="more"></a>
<h3 id="选择排序"><a href="#选择排序" class="headerlink" title="选择排序"></a>选择排序</h3><ul>
<li><p>基本思路<br>选择排序可以说是冒泡排序的改良版,通过循环对比，记录最小的数字下标与目标互换 这样相对于冒泡排序来说，比较的次数并没有改变，但是数据交换的次数大大减少。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b2349fb70?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">int</span> len = arr.length;</span><br><span class="line">		<span class="comment">// 用来保存每次比较后较小数的下标</span></span><br><span class="line">		<span class="keyword">int</span> minIndex;</span><br><span class="line">		<span class="comment">// i控制循环次数，长度为len的数组只需要循环len-1次，i的起始值为0所以i&lt;len-1</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len - <span class="number">1</span>; i++) &#123;</span><br><span class="line">			minIndex = i;</span><br><span class="line">			<span class="comment">//j控制比较次数，因为每次循环结束之后最小的数都已经放在了最前面，</span></span><br><span class="line">			<span class="comment">//所以下一次循环的时候就可以跳过这个数，所以j的初始值为i+1而不需要每次循环都从0开始，并且j&lt;len即可</span></span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = i + <span class="number">1</span>; j &lt; len; j++) &#123;</span><br><span class="line">				<span class="comment">// 每比较一次都需要将较小数的下标记录下来</span></span><br><span class="line">				<span class="keyword">if</span> (arr[minIndex] &gt; arr[j]) &#123;</span><br><span class="line">					minIndex = j;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 当完成一次循环时，就需要将本次循环选取的最小数移动到本次循环开始的位置。</span></span><br><span class="line">			<span class="keyword">if</span> (minIndex != i) &#123;</span><br><span class="line">				<span class="keyword">int</span> temp = arr[i];</span><br><span class="line">				arr[i] = arr[minIndex];</span><br><span class="line">				arr[minIndex] = temp;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="插入排序"><a href="#插入排序" class="headerlink" title="插入排序"></a>插入排序</h3><ul>
<li><p>基本思路<br>首先就默认数组中的第一个数的位置是正确的，即已经排序。然后取下一个数，与已经排序的数按从后向前的顺序依次比较， 如果该数比当前位置排好序的数小，则将排好序的数的位置向后移一位。 重复上一步骤，直到找到合适的位置。找到位置后就结束比较的循环，将该数放到相应的位置。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b284a6b98?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">int</span> len = arr.length;</span><br><span class="line">		<span class="comment">// target用来记录即将要排序的那个数的值即目标值</span></span><br><span class="line">		<span class="keyword">int</span> target;</span><br><span class="line">		<span class="comment">// index用来记录要交换的那个值的下标</span></span><br><span class="line">		<span class="keyword">int</span> index;</span><br><span class="line">		<span class="comment">// i控制循环次数，因为已经默认第一个数的位置是正确的，所以i的起始值为1，i&lt;len，循环len-1次</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; len; i++) &#123;</span><br><span class="line">			target = arr[i];</span><br><span class="line">			index = i;</span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = i; j &gt; <span class="number">0</span>; j--) &#123;</span><br><span class="line">				<span class="comment">// 如果前一个数大于target，则设值成后一个数，并记录前一个数下标</span></span><br><span class="line">				<span class="keyword">if</span> (target &lt; arr[j - <span class="number">1</span>]) &#123;</span><br><span class="line">					arr[j] = arr[j - <span class="number">1</span>];</span><br><span class="line">					index = j - <span class="number">1</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 更目标数的位置。</span></span><br><span class="line">			arr[index] = target;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="希尔排序"><a href="#希尔排序" class="headerlink" title="希尔排序"></a>希尔排序</h3><ul>
<li><p>基本思路<br>希尔排序也称为”缩小增量排序”，原理是先将需要排的数组分成多个子序列，这样每个子序列的元素个数就很少，再分别对每个对子序列进行插入排序。在该数组基本有序后 再进行一次直接插入排序就能完成对整个数组的排序。所以，要采用跳跃分割的策略。这里引入“增量”的概念，将相距某个增量的记录两两组合成一个子序列，然后对每个子序列进行直接插入排序， 这样得到的结果才会使基本有序（即小的在前边，大的在后边，不大不小的在中间）。希尔排序就是 直接插入排序的升级版。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b7d4cfe55?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	<span class="comment">// 数组的长度</span></span><br><span class="line">	<span class="keyword">int</span> len = arr.length;</span><br><span class="line">	<span class="comment">// 初始的增量为数组长度的一半</span></span><br><span class="line">	<span class="keyword">int</span> k = len / <span class="number">2</span>;</span><br><span class="line">	<span class="comment">// while循环控制按增量的值来划不同分子序列，每完成一次增量就减少为原来的一半</span></span><br><span class="line">	<span class="comment">// 增量的最小值为1，即最后一次对整个数组做直接插入排序</span></span><br><span class="line">	<span class="keyword">while</span> (k &gt; <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="comment">// 里边其实就是升级版的直接插入排序了，是对每一个子序列进行直接插入排序，</span></span><br><span class="line">		<span class="comment">// 所以直接将直接插入排序中的‘1’变为‘k’就可以了。</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = k; i &lt; len; i++) &#123;</span><br><span class="line">			<span class="keyword">int</span> j = i;</span><br><span class="line">			<span class="keyword">int</span> target = arr[i];</span><br><span class="line">			<span class="keyword">while</span> (j &gt;= k &amp;&amp; target &lt; arr[j - k]) &#123;</span><br><span class="line">				arr[j] = arr[j - k];</span><br><span class="line">				j -= k;</span><br><span class="line">			&#125;</span><br><span class="line">			arr[j] = target;</span><br><span class="line">		&#125;</span><br><span class="line">		k /= <span class="number">2</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h3><ul>
<li><p>基本思路<br>总体概括就是从上到下递归拆分，然后从下到上逐步合并。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b7f84849b?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 递归拆分</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> arr   待拆分数组</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> left  待拆分数组最小下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> right 待拆分数组最大下标</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">mergeSort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 中间下标</span></span><br><span class="line">		<span class="keyword">int</span> mid = (left + right) / <span class="number">2</span>;</span><br><span class="line">		<span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">			<span class="comment">// 递归拆分左边</span></span><br><span class="line">			mergeSort(arr, left, mid);</span><br><span class="line">			<span class="comment">// 递归拆分右边</span></span><br><span class="line">			mergeSort(arr, mid + <span class="number">1</span>, right);</span><br><span class="line">			<span class="comment">// 合并左右</span></span><br><span class="line">			sort(arr, left, mid, right);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 合并两个有序子序列</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> arr   待合并数组</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> left  待合并数组最小下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> mid   待合并数组中间下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> right 待合并数组最大下标</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> left, <span class="keyword">int</span> mid, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 临时数组，用来保存每次合并年之后的结果</span></span><br><span class="line">		<span class="keyword">int</span>[] temp = <span class="keyword">new</span> <span class="keyword">int</span>[right - left + <span class="number">1</span>];</span><br><span class="line">		<span class="keyword">int</span> i = left;</span><br><span class="line">		<span class="keyword">int</span> j = mid + <span class="number">1</span>;</span><br><span class="line">		<span class="comment">// 临时数组的初始下标</span></span><br><span class="line">		<span class="keyword">int</span> k = <span class="number">0</span>;</span><br><span class="line">		<span class="comment">// 这个while循环能够初步筛选出待合并的了两个子序列中的较小数</span></span><br><span class="line">		<span class="keyword">while</span> (i &lt;= mid &amp;&amp; j &lt;= right) &#123;</span><br><span class="line">			<span class="keyword">if</span> (arr[i] &lt;= arr[j]) &#123;</span><br><span class="line">				temp[k++] = arr[i++];</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				temp[k++] = arr[j++];</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将左边序列中剩余的数放入临时数组</span></span><br><span class="line">		<span class="keyword">while</span> (i &lt;= mid) &#123;</span><br><span class="line">			temp[k++] = arr[i++];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将右边序列中剩余的数放入临时数组</span></span><br><span class="line">		<span class="keyword">while</span> (j &lt;= right) &#123;</span><br><span class="line">			temp[k++] = arr[j++];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将临时数组中的元素位置对应到真真实的数组中</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> m = <span class="number">0</span>; m &lt; temp.length; m++) &#123;</span><br><span class="line">			arr[m + left] = temp[m];</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h3><ul>
<li><p>基本思路<br>快速排序也采用了分治的策略，这里引入了‘基准数’的概念。</p>
<ul>
<li>找一个基准数（一般将待排序的数组的第一个数作为基准数）</li>
<li>对数组进行分区，将小于等于基准数的全部放在左边，大于基准数的全部放在右边。</li>
<li>重复1，2步骤，分别对左右两个子分区进行分区，一直到各分区只有一个数为止。</li>
</ul>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01b83823cd8?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 分区过程</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> arr   待分区数组</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> left  待分区数组最小下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> right 待分区数组最大下标</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">quickSort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">			<span class="keyword">int</span> temp = qSort(arr, left, right);</span><br><span class="line">			quickSort(arr, left, temp - <span class="number">1</span>);</span><br><span class="line">			quickSort(arr, temp + <span class="number">1</span>, right);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 排序过程</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> arr   待排序数组</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> left  待排序数组最小下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> right 待排序数组最大下标</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 排好序之后基准数的位置下标，方便下次的分区</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">qSort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 定义基准数，默认为数组的第一个元素</span></span><br><span class="line">		<span class="keyword">int</span> temp = arr[left];</span><br><span class="line">		<span class="comment">// 循环执行的条件</span></span><br><span class="line">		<span class="keyword">while</span> (left &lt; right) &#123;</span><br><span class="line">			<span class="comment">// 因为默认的基准数是在最左边，所以首先从右边开始比较进入while循环的判断条件</span></span><br><span class="line">			<span class="comment">// 如果当前arr[right]比基准数大，则直接将右指针左移一位，当然还要保证left&lt;right</span></span><br><span class="line">			<span class="keyword">while</span> (left &lt; right &amp;&amp; arr[right] &gt; temp) &#123;</span><br><span class="line">				right--;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 跳出循环说明当前的arr[right]比基准数要小，那么直接将当前数移动到基准数所在的位置，并且左指针向右移一位（left++）</span></span><br><span class="line">			<span class="comment">// 这时当前数（arr[right]）所在的位置空出，需要从左边找一个比基准数大的数来填充。</span></span><br><span class="line">			<span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">				arr[left++] = arr[right];</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 下面的步骤是为了在左边找到比基准数大的数填充到right的位置。</span></span><br><span class="line">			<span class="comment">// 因为现在需要填充的位置在右边，所以左边的指针移动，如果arr[left]小于或者等于基准数，则直接将左指针右移一位</span></span><br><span class="line">			<span class="keyword">while</span> (left &lt; right &amp;&amp; arr[left] &lt;= temp) &#123;</span><br><span class="line">				left++;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 跳出上一个循环说明当前的arr[left]的值大于基准数，需要将该值填充到右边空出的位置，然后当前位置空出。</span></span><br><span class="line">			<span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">				arr[right--] = arr[left];</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 当循环结束说明左指针和右指针已经相遇。并且相遇的位置是一个空出的位置，</span></span><br><span class="line">		<span class="comment">// 这时候将基准数填入该位置，并返回该位置的下标，为分区做准备。</span></span><br><span class="line">		arr[left] = temp;</span><br><span class="line">		<span class="keyword">return</span> left;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h3><ul>
<li><p>基本思路<br>堆是一种特殊的完全二叉树，分为大顶堆和小顶堆。大顶堆：每个结点的值都大于它的左右子结点的值，升序排序用大顶堆。小顶堆：每个结点的值都小于它的左右子结点的值，降序排序用小顶堆。<br>所以，需要先将待排序数组构造成大顶堆的格式，这时候该堆的顶结点就是最大的数，将其与堆的最后一个结点的元素交换。再将剩余的树重新调整成堆，再次首节点与尾结点交换，重复执行直到只剩下最后一个结点完成排序。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bbe480b52?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">heapSort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (arr == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> len = arr.length;</span><br><span class="line">	<span class="comment">// 初始化大顶堆（从最后一个非叶节点开始，从左到右，由下到上）</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = len / <span class="number">2</span> - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">		adjustHeap(arr, i, len);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 将顶节点和最后一个节点互换位置，再将剩下的堆进行调整</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> j = len - <span class="number">1</span>; j &gt; <span class="number">0</span>; j--) &#123;</span><br><span class="line">		swap(arr, <span class="number">0</span>, j);</span><br><span class="line">		adjustHeap(arr, <span class="number">0</span>, j);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 整理树让其变成堆</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> arr 待整理的数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> i   开始的结点</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> j   数组的长度</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">adjustHeap</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 定义一个变量保存开始的结点</span></span><br><span class="line">	<span class="keyword">int</span> temp = arr[i];</span><br><span class="line">	<span class="comment">// k就是该结点的左子结点下标</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">2</span> * i + <span class="number">1</span>; k &lt; j; k = <span class="number">2</span> * k + <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="comment">// 比较左右两个子结点的大小，k始终记录两者中较大值的下标</span></span><br><span class="line">		<span class="keyword">if</span> (k + <span class="number">1</span> &lt; j &amp;&amp; arr[k] &lt; arr[k + <span class="number">1</span>]) &#123;</span><br><span class="line">			k++;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 经子结点中的较大值和当前的结点比较，比较结果的较大值放在当前结点位置</span></span><br><span class="line">		<span class="keyword">if</span> (arr[k] &gt; temp) &#123;</span><br><span class="line">			arr[i] = arr[k];</span><br><span class="line">			i = k;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// 说明已经是大顶堆</span></span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	arr[i] = temp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 交换数据</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> arr  待整理的数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> num1 开始的结点</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> num2 交换的节点</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> num1, <span class="keyword">int</span> num2)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> temp = arr[num1];</span><br><span class="line">	arr[num1] = arr[num2];</span><br><span class="line">	arr[num2] = temp;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="基数排序"><a href="#基数排序" class="headerlink" title="基数排序"></a>基数排序</h3><ul>
<li><p>基本思路<br>就是将待排序数据拆分成多个关键字进行排序，也就是说，基数排序的实质是多关键字排序。多关键字排序的思路是将待排数据里德排序关键字拆分成多个排序关键字；第1个排序关键字，第2个排序关键字，第3个排序关键字……然后，根据子关键字对待排序数据进行排序。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bd10a5893?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> radix, <span class="keyword">int</span> d)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 缓存数组  </span></span><br><span class="line">		<span class="keyword">int</span>[] tmp = <span class="keyword">new</span> <span class="keyword">int</span>[arr.length];</span><br><span class="line">		<span class="comment">// buckets用于记录待排序元素的信息  </span></span><br><span class="line">		<span class="comment">// buckets数组定义了max-min个桶  </span></span><br><span class="line">		<span class="keyword">int</span>[] buckets = <span class="keyword">new</span> <span class="keyword">int</span>[radix];</span><br><span class="line"></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, rate = <span class="number">1</span>; i &lt; d; i++) &#123;</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 重置count数组，开始统计下一个关键字  </span></span><br><span class="line">			java.util.Arrays.fill(buckets, <span class="number">0</span>);</span><br><span class="line">			<span class="comment">// 将data中的元素完全复制到tmp数组中  </span></span><br><span class="line">			System.arraycopy(arr, <span class="number">0</span>, tmp, <span class="number">0</span>, arr.length);</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 计算每个待排序数据的子关键字  </span></span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; arr.length; j++) &#123;</span><br><span class="line">				<span class="keyword">int</span> subKey = (tmp[j] / rate) % radix;</span><br><span class="line">				buckets[subKey]++;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt; radix; j++) &#123;</span><br><span class="line">				buckets[j] = buckets[j] + buckets[j - <span class="number">1</span>];</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="comment">// 按子关键字对指定的数据进行排序  </span></span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> m = arr.length - <span class="number">1</span>; m &gt;= <span class="number">0</span>; m--) &#123;</span><br><span class="line">				<span class="keyword">int</span> subKey = (tmp[m] / rate) % radix;</span><br><span class="line">				arr[--buckets[subKey]] = tmp[m];</span><br><span class="line">			&#125;</span><br><span class="line">			rate *= radix;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="计数排序"><a href="#计数排序" class="headerlink" title="计数排序"></a>计数排序</h3><ul>
<li><p>基本思路<br>计数排序采用了一种全新的思路，不再是通过比较来排序，而是将待排序数组中的最大值+1作为一个临时数组的长度，然后用临时数组记录待排序数组中每个元素出现的次数。最后再遍历临时数组，因为是升序，所以从前到后遍历，将临时数组中值&gt;0的数的下标循环取出，依次放入待排序数组中，即可完成排序。计数排序的效率很高，但是实在牺牲内存的前提下，并且有着限制，那就是待排序数组的值必须 限制在一个确定的范围。</p>
</li>
<li><p>动图演示</p>
</li>
</ul>
<p><img src="https://user-gold-cdn.xitu.io/2019/1/17/1685c01bbf2b9faf?imageslim" alt="这里写图片描述"></p>
<ul>
<li>编码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">int</span> len = arr.length;</span><br><span class="line">		<span class="comment">// 保存待排序数组中的最大值，目的是确定临时数组的长度（必须）</span></span><br><span class="line">		<span class="keyword">int</span> maxNum = arr[<span class="number">0</span>];</span><br><span class="line">		<span class="comment">// 保存待排序数组中的最小值，目的是确定最终遍历临时数组时下标的初始值（非必需，只是这样可以加快速度，减少循环次数）</span></span><br><span class="line">		<span class="keyword">int</span> minNum = arr[<span class="number">0</span>];</span><br><span class="line">		<span class="comment">// for循环就是为了找到待排序数组的最大值和最小值</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; len; i++) &#123;</span><br><span class="line">			maxNum = maxNum &gt; arr[i] ? maxNum : arr[i];</span><br><span class="line">			minNum = minNum &lt; arr[i] ? minNum : arr[i];</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 创建一个临时数组</span></span><br><span class="line">		<span class="keyword">int</span>[] temp = <span class="keyword">new</span> <span class="keyword">int</span>[maxNum + <span class="number">1</span>];</span><br><span class="line">		<span class="comment">// for循环是为了记录待排序数组中每个元素出现的次数，并将该次数保存到临时数组中</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> anArr : arr) &#123;</span><br><span class="line">			temp[anArr]++;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// k=0用来记录待排序数组的下标</span></span><br><span class="line">		<span class="keyword">int</span> k = <span class="number">0</span>;</span><br><span class="line">		<span class="comment">// 遍历临时数组，重新为待排序数组赋值。</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = minNum; i &lt; temp.length; i++) &#123;</span><br><span class="line">			<span class="keyword">while</span> (temp[i] &gt; <span class="number">0</span>) &#123;</span><br><span class="line">				arr[k++] = i;</span><br><span class="line">				temp[i]--;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="桶排序"><a href="#桶排序" class="headerlink" title="桶排序"></a>桶排序</h3><ul>
<li><p>基本思路<br>桶排序其实就是计数排序的强化版，需要利用一个映射函数首先定义有限个数个桶，然后将待排序数组内的元素按照函数映射的关系分别放入不同的桶里边，现在不同的桶里边的数据已经做了区分，比如A桶里的数要么全部大于B桶，要么全部小于B桶里的数。但是A，B桶各自里边的数还是乱序的。所以要借助其他排序方式（快速，插入，归并）分别对每一个元素个数大于一的桶里边的数据进行排序。最后再将桶里边的元素按照顺序依次放入待排序数组中即可。</p>
</li>
<li><p>动图演示<br>无。。。。。</p>
</li>
<li><p>编码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (arr == <span class="keyword">null</span>)</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		<span class="keyword">int</span> len = arr.length;</span><br><span class="line">		<span class="comment">// 定义桶的个数，这里k的值要视情况而定，这里我们假设待排序数组里的数都是[0,100)之间的。</span></span><br><span class="line">		<span class="keyword">int</span> k = <span class="number">10</span>;</span><br><span class="line">		<span class="comment">// 用嵌套集合来模拟桶，外层集合表示桶，内层集合表示桶里边装的元素。</span></span><br><span class="line">		java.util.List&lt;java.util.List&lt;Integer&gt;&gt; bucket = <span class="keyword">new</span> java.util.ArrayList&lt;&gt;();</span><br><span class="line">		<span class="comment">// for循环初始化外层集合即初始化桶</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; k; i++) &#123;</span><br><span class="line">			bucket.add(<span class="keyword">new</span> java.util.ArrayList&lt;&gt;());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 循环是为了将待排序数组中的元素通过映射函数分别放入不同的桶里边</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> anArr : arr) &#123;</span><br><span class="line">			bucket.get(anArr / <span class="number">10</span>).add(anArr);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 这个循环是为了将所有的元素个数大于1的桶里边的数据进行排序。</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; k; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (bucket.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">				<span class="comment">// 因为这里是用集合来模拟的桶所以用java写好的对集合排序的方法。</span></span><br><span class="line">				<span class="comment">// 其实应该自己写一个方法来排序的。</span></span><br><span class="line">				java.util.Collections.sort(bucket.get(i));</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将排好序的数重新放入待排序数组中</span></span><br><span class="line">		<span class="keyword">int</span> m = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span> (java.util.List&lt;Integer&gt; list : bucket) &#123;</span><br><span class="line">			<span class="keyword">if</span> (list.size() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">				<span class="keyword">for</span> (Integer a : list) &#123;</span><br><span class="line">					arr[m++] = a;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>

    

    
    
    

    

    

    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">
            -------------本文结束
            <i class="fa fa-paw"></i>
            感谢您的阅读-------------
        </div>
    
</div>

      
    </div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/little-eight-china.github.io/tags/little-eight/" rel="tag"># little_eight</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/little-eight-china.github.io/2018/12/28/Linux命令大全/" rel="next" title="Linux命令大全">
                <i class="fa fa-chevron-left"></i> Linux命令大全
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/little-eight-china.github.io/2019/02/15/使用Nacos实现服务注册与发现/" rel="prev" title="使用Nacos实现服务注册与发现">
                使用Nacos实现服务注册与发现 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODE4Ni8xNDcxNA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/little-eight-china.github.io/archives/">
                
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/little-eight-china.github.io/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/little-eight-china.github.io/tags/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/little-eight-china" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://blog.csdn.net/h295928126" target="_blank" title="CSDN"><i class="fa fa-fw fa-crosshairs"></i>CSDN</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                成人链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://acris.me/" title="acris" target="_blank">acris</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#十大基础排序算法"><span class="nav-number">1.</span> <span class="nav-text">十大基础排序算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#冒泡排序"><span class="nav-number">1.1.</span> <span class="nav-text">冒泡排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#选择排序"><span class="nav-number">1.2.</span> <span class="nav-text">选择排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#插入排序"><span class="nav-number">1.3.</span> <span class="nav-text">插入排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#希尔排序"><span class="nav-number">1.4.</span> <span class="nav-text">希尔排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#归并排序"><span class="nav-number">1.5.</span> <span class="nav-text">归并排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#快速排序"><span class="nav-number">1.6.</span> <span class="nav-text">快速排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#堆排序"><span class="nav-number">1.7.</span> <span class="nav-text">堆排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基数排序"><span class="nav-number">1.8.</span> <span class="nav-text">基数排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#计数排序"><span class="nav-number">1.9.</span> <span class="nav-text">计数排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#桶排序"><span class="nav-number">1.10.</span> <span class="nav-text">桶排序</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  

  
</div>



<!-- 统计访问数 -->
<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>

        








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/little-eight-china.github.io/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/little-eight-china.github.io/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/little-eight-china.github.io/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/little-eight-china.github.io/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/little-eight-china.github.io/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/little-eight-china.github.io/js/src/bootstrap.js?v=6.3.0"></script>



  



  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/little-eight-china.github.io/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
